package com.hyg.lib_common.WebView;

import android.annotation.TargetApi;
import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;


import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.hyg.lib_base.Net.NetworkUtils;
import com.hyg.lib_base.WebViewUtil.HostSonicRuntime;
import com.hyg.lib_base.WebViewUtil.SonicJavaScriptInterface;
import com.hyg.lib_base.WebViewUtil.SonicSessionClientImpl;
import com.hyg.lib_base.mainUtils.StatusBarUtil;
import com.hyg.lib_base.mainUtils.Utils;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.R;
import com.tencent.sonic.sdk.SonicConfig;
import com.tencent.sonic.sdk.SonicEngine;
import com.tencent.sonic.sdk.SonicSession;
import com.tencent.sonic.sdk.SonicSessionConfig;

import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URLDecoder;
import java.util.Timer;
import java.util.TimerTask;


//指定  本Activity 的唯一路由地址 (必须 “/” 开头，并且地址中含两个以上“/”才行)
@Route(path = "/common/WebViewActivity")
public class WebViewActivity extends BaseActivity {

    private String url;
    private SonicSession sonicSession;
    private WebView webView;
    private Button back;
    private TextView timertext;
    private int countdown = 3;
//    private RefreshLayout refreshLayout;
    private ImageView refresh;
    private TextView title;

    @Autowired
    Bundle bundle;

    private MyHandler myHandler = new MyHandler(this);
    private static class MyHandler extends Handler {
        private final WeakReference<Context> reference;
        private WebViewActivity activity;
        public MyHandler(Context context) {
            reference = new WeakReference<>(context);
            activity = (WebViewActivity) reference.get();
        }
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 101:
                    activity.timertext.setText(activity.countdown + "");
                    if (0 == activity.countdown) {
                        //停止倒计时显示页面
                        activity.finish();
                        activity.overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
                        return;
                    }
//                    if (activity.pDialog.isShowing()) {
                        activity.countdown--;
//                    }
                    break;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        StatusBarUtil.setStatusBar(3, this, getResources().getColor(R.color.white), 10, null, null, true);
        webView = (WebView) findViewById(R.id.webview);
        title = (TextView)findViewById(R.id.title);
        refresh = (ImageView)findViewById(R.id.refresh);
        back = (Button)findViewById(R.id.bt_back);
//        refreshLayout = (RefreshLayout)findViewById(R.id.refreshLayout);
        initView();
        init();
    }

    private void init(){

        back.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                back_finish_activity(true);
            }
        });

        final Animation rotate = AnimationUtils.loadAnimation(this, R.anim.rotate_anim);
        refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(Utils.isFastClick())return;
                refresh.startAnimation(rotate);
                webView.reload();
//                refresh.clearAnimation();
            }
        });

    }

    private void initView() {
        try {
//            if(!Utils.isEmpty(bundle.getString("title"))){
//                title.setText(bundle.getString("title"));
//            }
//            url = URLDecoder.decode(bundle.getString("url"), "UTF-8");
//            Log.d("url", url);
            if(!Utils.isEmpty(getIntent().getStringExtra("title"))){
                title.setText(getIntent().getStringExtra("title"));
            }
            url = URLDecoder.decode(getIntent().getStringExtra("url"), "UTF-8");

            if (Utils.isEmpty(url)) {
                dialogShow();
                return;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        //步骤1：如有必要初始化声音引擎，或者也许当应用程序创建u能做到这一点
        // step 1: Initialize sonic engine if necessary, or maybe u can do this when application created
        if (!SonicEngine.isGetInstanceAllowed()) {
            SonicEngine.createInstance(new HostSonicRuntime(getApplication()), new SonicConfig.Builder().build());
        }
        SonicSessionClientImpl sonicSessionClient = null;
        //步骤2：创建SonicSession
        // step 2: Create SonicSession
        sonicSession = SonicEngine.getInstance().createSession(url, new SonicSessionConfig.Builder().build());
        if (null != sonicSession) {
            sonicSession.bindClient(sonicSessionClient = new SonicSessionClientImpl());
        } else {
            // this only happen when a same sonic session is already running,
            // u can comment following codes to feedback as a default mode.
            //只有在同一个声音会话已经运行时才会发生，
            //可以将以下代码注释为默认模式。
            //            throw new UnknownError("create session fail!");
        }

        //步骤3：BindWebView为sessionClient和bindClient为SonicSession
        //在现实世界中，init流可能花费很长的时间在启动
        //运行时，初始化CONFIGS ....
        // step 3: BindWebView for sessionClient and bindClient for SonicSession
        // in the real world, the init flow may cost a long time as startup
        // runtime、init configs....

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (sonicSession != null) {
                    sonicSession.getSessionClient().pageFinish(url);
                }
            }

            @TargetApi(21)
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                return shouldInterceptRequest(view, request.getUrl().toString());
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                if (sonicSession != null) {
                    //step 6: Call sessionClient.requestResource when host allow the application
                    // to return the local data .
                    return (WebResourceResponse) sonicSession.getSessionClient().requestResource(url);
                }
                return null;
            }
        });

        WebSettings webSettings = webView.getSettings();

        // step 4: bind javascript
        // note:if api level lower than 17(android 4.2), addJavascriptInterface has security
        // issue, please use x5 or see https://developer.android.com/reference/android/webkit/
        // WebView.html#addJavascriptInterface(java.lang.Object, java.lang.String)
        //步骤4：绑定javascript
        //注意：如果api级别低于17（android 4.2），addJavascriptInterface有安全性
        //问题，请使用x5或参见https://developer.android.com/reference/android/webkit/
        // WebView.html＃addJavascriptInterface（java.lang.Object，java.lang.String）
        webSettings.setJavaScriptEnabled(true);
        webView.removeJavascriptInterface("searchBoxJavaBridge_");
        Intent it = new Intent();
        it.putExtra(SonicJavaScriptInterface.PARAM_LOAD_URL_TIME, System.currentTimeMillis());
        webView.addJavascriptInterface(new SonicJavaScriptInterface(sonicSessionClient, it), "sonic");

        // init webview settings
        webSettings.setAllowContentAccess(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheEnabled(true);
//        webSettings.setSavePassword(false);
        webSettings.setSaveFormData(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        //支持屏幕缩放
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        //不显示webview缩放按钮
        webSettings.setDisplayZoomControls(false);

        //步骤5：webview已经准备就绪，只需告诉会话客户端绑定
        // step 5: webview is ready now, just tell session client to bind
        if (sonicSessionClient != null) {
            sonicSessionClient.bindWebView(webView);
            sonicSessionClient.clientReady();
        } else { // default mode//默认模式
//            setDataFrom();
            webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
            webView.loadUrl(url);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            webView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
                @Override
                public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                    Log.d("scroll",scrollY+"");
                }
            });
        }
    }

    public void setDataFrom() {
        if (NetworkUtils.isConnected(this)) {
            webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        } else {
            webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ONLY);
//            UINetWork(NetworkUtils.isConnected(this));
        }
    }

    public void dialogShow() {
        View view = View.inflate(getApplicationContext(), R.layout.dialog_layouts, null);
        timertext = view.findViewById(R.id.tv_dialog);
        timertext.setGravity(Gravity.CENTER);
        final Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            public void run() {
                myHandler.sendEmptyMessage(101);
            }
        };
        countdown = 3;
//        pDialog = new SweetAlertDialog(this, SweetAlertDialog.ERROR_TYPE);
//        pDialog.setTitleText("当前链接非有效页面，即将返回");
//        pDialog.setCustomView(view);
//        pDialog.setConfirmButton("好的", new SweetAlertDialog.OnSweetClickListener() {
//            public void onClick(SweetAlertDialog sweetAlertDialog) {
//                timer.cancel();
//                sweetAlertDialog.dismiss();
//                back_finish_activity(true);
//                overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
//            }
//        });
//        pDialog.show();
        timer.schedule(timerTask, 500, 1000);
    }

    public void actionKey(final int keyCode) {
        new Thread() {
            public void run() {
                try {
                    Instrumentation inst = new Instrumentation();
                    inst.sendKeyDownUpSync(keyCode);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (webView.canGoBack()) {
                webView.goBack();//返回上一页面
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        if (null != sonicSession) {
            sonicSession.destroy();
            sonicSession = null;
        }
        super.onDestroy();
    }
}
